{% extends "base.html" %}

{% block title %}系统监控 - MinerU 文档解析系统{% endblock %}

{% block page_title %}系统监控{% endblock %}

{% block content %}
<div class="fade-in">
    <!-- 监控配置状态 -->
    <div class="bg-white rounded-xl shadow-sm p-6 mb-6">
        <div class="flex items-center justify-between mb-4">
            <h3 class="text-lg font-semibold text-gray-800">监控配置状态</h3>
            <div class="flex items-center space-x-2">
                <span class="text-sm text-gray-600">数据保存:</span>
                <span class="px-2 py-1 text-xs font-medium rounded-full {% if metrics_config.save_metrics_to_db %}bg-green-100 text-green-800{% else %}bg-red-100 text-red-800{% endif %}">
                    {% if metrics_config.save_metrics_to_db %}已启用{% else %}已禁用{% endif %}
                </span>
            </div>
        </div>
        <div class="grid grid-cols-1 md:grid-cols-4 gap-4 text-sm">
            <div>
                <span class="text-gray-600">数据保留:</span>
                <span class="ml-2 font-medium">{{ metrics_config.metrics_retention_days }} 天</span>
            </div>
            <div>
                <span class="text-gray-600">收集间隔:</span>
                <span class="ml-2 font-medium">{{ metrics_config.metrics_collection_interval }} 秒</span>
            </div>
            <div>
                <span class="text-gray-600">系统监控:</span>
                <span class="ml-2 font-medium {% if metrics_config.enable_system_monitoring %}text-green-600{% else %}text-red-600{% endif %}">
                    {% if metrics_config.enable_system_monitoring %}启用{% else %}禁用{% endif %}
                </span>
            </div>
            <div>
                <span class="text-gray-600">总记录数:</span>
                <span class="ml-2 font-medium" id="totalRecords">加载中...</span>
            </div>
        </div>
    </div>

    <!-- 实时监控卡片 -->
    <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
        <div class="bg-white rounded-xl shadow-sm p-6 hover-scale">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm text-gray-500 mb-1">CPU 使用率</p>
                    <p class="text-2xl font-bold text-gray-800" id="currentCpu">--</p>
                    <p class="text-sm text-gray-600 mt-1" id="cpuStatus">--</p>
                </div>
                <div class="w-12 h-12 bg-blue-100 rounded-lg flex items-center justify-center">
                    <i class="fas fa-microchip text-blue-600 text-xl"></i>
                </div>
            </div>
        </div>
        
        <div class="bg-white rounded-xl shadow-sm p-6 hover-scale">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm text-gray-500 mb-1">内存使用率</p>
                    <p class="text-2xl font-bold text-gray-800" id="currentMemory">--</p>
                    <p class="text-sm text-gray-600 mt-1" id="memoryStatus">--</p>
                </div>
                <div class="w-12 h-12 bg-green-100 rounded-lg flex items-center justify-center">
                    <i class="fas fa-memory text-green-600 text-xl"></i>
                </div>
            </div>
        </div>
        
        <div class="bg-white rounded-xl shadow-sm p-6 hover-scale">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm text-gray-500 mb-1">磁盘使用率</p>
                    <p class="text-2xl font-bold text-gray-800" id="currentDisk">--</p>
                    <p class="text-sm text-gray-600 mt-1" id="diskStatus">--</p>
                </div>
                <div class="w-12 h-12 bg-orange-100 rounded-lg flex items-center justify-center">
                    <i class="fas fa-hdd text-orange-600 text-xl"></i>
                </div>
            </div>
        </div>
        
        <div class="bg-white rounded-xl shadow-sm p-6 hover-scale">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm text-gray-500 mb-1">系统状态</p>
                    <p class="text-2xl font-bold text-gray-800" id="systemStatus">--</p>
                    <p class="text-sm text-gray-600 mt-1" id="uptime">--</p>
                </div>
                <div class="w-12 h-12 bg-purple-100 rounded-lg flex items-center justify-center">
                    <i class="fas fa-server text-purple-600 text-xl"></i>
                </div>
            </div>
        </div>
    </div>

    <!-- 历史数据图表 -->
    <div class="bg-white rounded-xl shadow-sm p-6 mb-8">
        <div class="flex justify-between items-center mb-6">
            <h3 class="text-lg font-semibold text-gray-800">历史监控数据</h3>
            <div class="flex items-center space-x-4">
                <select id="timeRange" class="px-3 py-2 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
                    <option value="1">最近 1 小时</option>
                    <option value="6">最近 6 小时</option>
                    <option value="24" selected>最近 24 小时</option>
                    <option value="72">最近 3 天</option>
                    <option value="168">最近 7 天</option>
                </select>
                <button id="refreshBtn" class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors text-sm">
                    <i class="fas fa-sync-alt mr-2"></i>刷新
                </button>
            </div>
        </div>
        
        <!-- 统计摘要 -->
        <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6" id="summaryCards">
            <div class="bg-gray-50 rounded-lg p-4">
                <h4 class="text-sm font-medium text-gray-600 mb-2">CPU 统计</h4>
                <div class="space-y-1 text-sm">
                    <div class="flex justify-between">
                        <span>平均:</span>
                        <span id="avgCpu">--</span>
                    </div>
                    <div class="flex justify-between">
                        <span>最高:</span>
                        <span id="maxCpu">--</span>
                    </div>
                    <div class="flex justify-between">
                        <span>最低:</span>
                        <span id="minCpu">--</span>
                    </div>
                </div>
            </div>
            
            <div class="bg-gray-50 rounded-lg p-4">
                <h4 class="text-sm font-medium text-gray-600 mb-2">内存统计</h4>
                <div class="space-y-1 text-sm">
                    <div class="flex justify-between">
                        <span>平均:</span>
                        <span id="avgMemory">--</span>
                    </div>
                    <div class="flex justify-between">
                        <span>最高:</span>
                        <span id="maxMemory">--</span>
                    </div>
                    <div class="flex justify-between">
                        <span>最低:</span>
                        <span id="minMemory">--</span>
                    </div>
                </div>
            </div>
            
            <div class="bg-gray-50 rounded-lg p-4">
                <h4 class="text-sm font-medium text-gray-600 mb-2">磁盘统计</h4>
                <div class="space-y-1 text-sm">
                    <div class="flex justify-between">
                        <span>平均:</span>
                        <span id="avgDisk">--</span>
                    </div>
                    <div class="flex justify-between">
                        <span>最高:</span>
                        <span id="maxDisk">--</span>
                    </div>
                    <div class="flex justify-between">
                        <span>最低:</span>
                        <span id="minDisk">--</span>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 图表容器 -->
        <div class="h-96 flex items-center justify-center" id="chartContainer">
            <div class="text-center">
                <i class="fas fa-chart-line text-4xl text-gray-300 mb-4"></i>
                <p class="text-gray-500">图表将在这里显示</p>
                <p class="text-sm text-gray-400 mt-2">请确保已启用监控数据保存功能</p>
            </div>
        </div>
    </div>

    <!-- 历史数据表格 -->
    <div class="bg-white rounded-xl shadow-sm p-6">
        <div class="flex justify-between items-center mb-6">
            <h3 class="text-lg font-semibold text-gray-800">历史记录</h3>
            <div class="flex items-center space-x-2">
                <input type="number" id="limitInput" placeholder="记录数" min="1" max="1000" value="50" 
                       class="px-3 py-2 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
                <button id="loadHistoryBtn" class="px-4 py-2 bg-gray-600 text-white rounded-lg hover:bg-gray-700 transition-colors text-sm">
                    加载记录
                </button>
            </div>
        </div>
        
        <div class="overflow-x-auto">
            <table class="w-full">
                <thead>
                    <tr class="border-b">
                        <th class="text-left py-3 px-4 text-sm font-medium text-gray-600">时间</th>
                        <th class="text-left py-3 px-4 text-sm font-medium text-gray-600">CPU</th>
                        <th class="text-left py-3 px-4 text-sm font-medium text-gray-600">内存</th>
                        <th class="text-left py-3 px-4 text-sm font-medium text-gray-600">磁盘</th>
                        <th class="text-left py-3 px-4 text-sm font-medium text-gray-600">状态</th>
                        <th class="text-left py-3 px-4 text-sm font-medium text-gray-600">进程数</th>
                        <th class="text-left py-3 px-4 text-sm font-medium text-gray-600">线程数</th>
                    </tr>
                </thead>
                <tbody id="historyTable">
                    <tr class="border-b hover:bg-gray-50">
                        <td class="py-3 px-4 text-sm text-gray-800" colspan="7">
                            <div class="text-center py-8">
                                <i class="fas fa-spinner fa-spin text-2xl text-gray-400 mb-2"></i>
                                <p class="text-gray-500">加载中...</p>
                            </div>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
// 全局变量
let chart = null;
let refreshInterval = null;

// 页面加载时初始化
document.addEventListener('DOMContentLoaded', async function() {
    await loadMetricsConfig();
    await loadCurrentMetrics();
    await loadSummaryData();
    await loadHistoryData();
    
    // 启动定时刷新
    startAutoRefresh();
    
    // 绑定事件
    bindEvents();
});

// 加载监控配置
async function loadMetricsConfig() {
    try {
        const response = await apiRequest('/api/v1/system/metrics/config');
        if (response.success) {
            const config = response.config;
            // 配置已经在模板中渲染，这里主要是为了检查是否启用
            if (!config.save_metrics_to_db) {
                showNotification('系统监控数据保存功能未启用，请联系管理员启用', 'warning');
            }
        }
    } catch (error) {
        console.error('加载监控配置失败:', error);
    }
}

// 加载当前监控数据
async function loadCurrentMetrics() {
    try {
        const metrics = await apiRequest('/api/v1/system/metrics/simple');
        
        // 更新实时数据
        document.getElementById('currentCpu').textContent = metrics.cpu.toFixed(1) + '%';
        document.getElementById('currentMemory').textContent = metrics.memory.toFixed(1) + '%';
        document.getElementById('currentDisk').textContent = metrics.disk.toFixed(1) + '%';
        document.getElementById('systemStatus').textContent = metrics.status;
        
        // 更新状态指示
        updateStatusIndicator('cpuStatus', metrics.cpu);
        updateStatusIndicator('memoryStatus', metrics.memory);
        updateStatusIndicator('diskStatus', metrics.disk);
        
        // 更新运行时间
        if (metrics.uptime) {
            document.getElementById('uptime').textContent = formatUptime(metrics.uptime);
        }
        
    } catch (error) {
        console.error('加载当前监控数据失败:', error);
    }
}

// 加载统计摘要数据
async function loadSummaryData() {
    try {
        const hours = document.getElementById('timeRange').value;
        const response = await apiRequest(`/api/v1/system/metrics/summary?hours=${hours}`);
        
        if (response.success) {
            const summary = response.data;
            
            // 更新统计卡片
            document.getElementById('avgCpu').textContent = summary.avg_cpu.toFixed(1) + '%';
            document.getElementById('maxCpu').textContent = summary.max_cpu.toFixed(1) + '%';
            document.getElementById('minCpu').textContent = summary.min_cpu.toFixed(1) + '%';
            
            document.getElementById('avgMemory').textContent = summary.avg_memory.toFixed(1) + '%';
            document.getElementById('maxMemory').textContent = summary.max_memory.toFixed(1) + '%';
            document.getElementById('minMemory').textContent = summary.min_memory.toFixed(1) + '%';
            
            document.getElementById('avgDisk').textContent = summary.avg_disk.toFixed(1) + '%';
            document.getElementById('maxDisk').textContent = summary.max_disk.toFixed(1) + '%';
            document.getElementById('minDisk').textContent = summary.min_disk.toFixed(1) + '%';
            
            // 更新总记录数
            document.getElementById('totalRecords').textContent = summary.total_records || 0;
            
            // 更新图表
            updateChart(summary);
        } else {
            // 显示未启用提示
            document.getElementById('summaryCards').innerHTML = `
                <div class="col-span-3 text-center py-8">
                    <i class="fas fa-exclamation-triangle text-3xl text-yellow-500 mb-3"></i>
                    <p class="text-gray-600">${response.message}</p>
                </div>
            `;
        }
    } catch (error) {
        console.error('加载统计摘要失败:', error);
    }
}

// 加载历史数据
async function loadHistoryData() {
    try {
        const limit = document.getElementById('limitInput').value;
        const hours = document.getElementById('timeRange').value;
        const response = await apiRequest(`/api/v1/system/metrics/history?hours=${hours}&limit=${limit}`);
        
        const tbody = document.getElementById('historyTable');
        
        if (response.success && response.data.length > 0) {
            tbody.innerHTML = response.data.map(record => `
                <tr class="border-b hover:bg-gray-50">
                    <td class="py-3 px-4 text-sm text-gray-600">${formatDateTime(record.timestamp)}</td>
                    <td class="py-3 px-4 text-sm text-gray-800">${record.cpu_percent.toFixed(1)}%</td>
                    <td class="py-3 px-4 text-sm text-gray-800">${record.memory_percent.toFixed(1)}%</td>
                    <td class="py-3 px-4 text-sm text-gray-800">${record.disk_percent.toFixed(1)}%</td>
                    <td class="py-3 px-4">
                        <span class="status-badge status-${record.status}">
                            <i class="fas fa-${getStatusIcon(record.status)} mr-1"></i>
                            ${record.status}
                        </span>
                    </td>
                    <td class="py-3 px-4 text-sm text-gray-800">${record.process_count}</td>
                    <td class="py-3 px-4 text-sm text-gray-800">${record.thread_count}</td>
                </tr>
            `).join('');
        } else {
            tbody.innerHTML = `
                <tr class="border-b hover:bg-gray-50">
                    <td class="py-3 px-4 text-sm text-gray-800" colspan="7">
                        <div class="text-center py-8">
                            <i class="fas fa-inbox text-2xl text-gray-400 mb-2"></i>
                            <p class="text-gray-500">${response.message || '暂无历史数据'}</p>
                        </div>
                    </td>
                </tr>
            `;
        }
    } catch (error) {
        console.error('加载历史数据失败:', error);
        document.getElementById('historyTable').innerHTML = `
            <tr class="border-b hover:bg-gray-50">
                <td class="py-3 px-4 text-sm text-gray-800" colspan="7">
                    <div class="text-center py-8">
                        <i class="fas fa-exclamation-triangle text-2xl text-gray-400 mb-2"></i>
                        <p class="text-gray-500">加载失败</p>
                    </div>
                </td>
            </tr>
        `;
    }
}

// 绑定事件
function bindEvents() {
    // 刷新按钮
    document.getElementById('refreshBtn').addEventListener('click', async function() {
        await refreshAllData();
    });
    
    // 时间范围选择
    document.getElementById('timeRange').addEventListener('change', async function() {
        await loadSummaryData();
        await loadHistoryData();
    });
    
    // 加载历史记录按钮
    document.getElementById('loadHistoryBtn').addEventListener('click', async function() {
        await loadHistoryData();
    });
}

// 刷新所有数据
async function refreshAllData() {
    const btn = document.getElementById('refreshBtn');
    const originalContent = btn.innerHTML;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>刷新中...';
    btn.disabled = true;
    
    try {
        await Promise.all([
            loadCurrentMetrics(),
            loadSummaryData(),
            loadHistoryData()
        ]);
        showNotification('数据刷新成功', 'success');
    } catch (error) {
        showNotification('数据刷新失败', 'error');
    } finally {
        btn.innerHTML = originalContent;
        btn.disabled = false;
    }
}

// 启动自动刷新
function startAutoRefresh() {
    // 每30秒刷新一次当前数据
    refreshInterval = setInterval(async () => {
        await loadCurrentMetrics();
    }, 30000);
}

// 停止自动刷新
function stopAutoRefresh() {
    if (refreshInterval) {
        clearInterval(refreshInterval);
        refreshInterval = null;
    }
}

// 更新状态指示器
function updateStatusIndicator(elementId, value) {
    const element = document.getElementById(elementId);
    let status = '正常';
    let colorClass = 'text-green-600';
    
    if (value > 80) {
        status = '高负载';
        colorClass = 'text-red-600';
    } else if (value > 60) {
        status = '中等负载';
        colorClass = 'text-orange-600';
    }
    
    element.textContent = status;
    element.className = `text-sm ${colorClass}`;
}

// 更新图表（简化版本）
function updateChart(summary) {
    const container = document.getElementById('chartContainer');
    container.innerHTML = `
        <div class="grid grid-cols-1 md:grid-cols-3 gap-4 w-full">
            <div class="text-center">
                <div class="text-2xl font-bold text-blue-600">${summary.avg_cpu.toFixed(1)}%</div>
                <div class="text-sm text-gray-600">平均 CPU</div>
            </div>
            <div class="text-center">
                <div class="text-2xl font-bold text-green-600">${summary.avg_memory.toFixed(1)}%</div>
                <div class="text-sm text-gray-600">平均内存</div>
            </div>
            <div class="text-center">
                <div class="text-2xl font-bold text-orange-600">${summary.avg_disk.toFixed(1)}%</div>
                <div class="text-sm text-gray-600">平均磁盘</div>
            </div>
        </div>
        <div class="mt-4 text-center">
            <p class="text-sm text-gray-500">数据时间范围: ${summary.time_range_hours} 小时</p>
            <p class="text-sm text-gray-500">总记录数: ${summary.total_records}</p>
        </div>
    `;
}

// 辅助函数
function getStatusIcon(status) {
    const icons = {
        'normal': 'check-circle',
        'warning': 'exclamation-triangle',
        'critical': 'times-circle'
    };
    return icons[status] || 'question-circle';
}

function formatDateTime(timestamp) {
    return new Date(timestamp).toLocaleString('zh-CN');
}

function formatUptime(seconds) {
    const days = Math.floor(seconds / 86400);
    const hours = Math.floor((seconds % 86400) / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);
    
    if (days > 0) {
        return `${days}天 ${hours}小时`;
    } else if (hours > 0) {
        return `${hours}小时 ${minutes}分钟`;
    } else {
        return `${minutes}分钟`;
    }
}

// 页面卸载时清理
window.addEventListener('beforeunload', () => {
    stopAutoRefresh();
});
</script>
{% endblock %}